﻿scene.mesh.content = (function ($, undefined)
{
    var _container = null;
    var _scene = null;
    var _camera = null;

    var init = function (container, scene, camera)
    {
        _container = container;
        _scene = scene;
        _camera = camera;
        
        _container.click(function (event) {
            _onDocumentMouseClick(event);
        });
    };
    
    var destroy = function ()
    {
    };

    var _onDocumentMouseClick = function(event)
    {
        var mouse = { x: 0, y: 0 };

        var width = _container.width(),
            height = _container.height();

        mouse.x = (event.offsetX / width) * 2 - 1;
        mouse.y = -(event.offsetY / height) * 2 + 1;

        // create a Ray with origin at the mouse position and direction into the scene (camera direction)
        var vector = new THREE.Vector3(mouse.x, mouse.y, 1);

        // initialize object to perform world/screen calculations
        var projector = new THREE.Projector();
        projector.unprojectVector(vector, _camera);

        var ray = new THREE.Raycaster(_camera.position, vector.sub(_camera.position).normalize());

        // create an array containing all objects in the scene with which the ray intersects
        var intersects = ray.intersectObjects(_scene.children);

        // if there is one (or more) intersections
        if (intersects.length > 0) {
            $('.loading').show();
            var identifier = intersects[0].object.identifier;
            var documentContentUrl = '/api/document/' + identifier + '/content';
            $.getJSON(documentContentUrl)
                .done(function(data) {
                    $('.loading').hide();
                    var $documentContent = $('.document_content');
                    $documentContent.text(data);
                });
        }
    };

    // public API
    return {
        init: init,
        destroy: destroy
    };
})(jQuery);